Adding .svg on html page

Vector Graphics - svg files

Created: 2022-09-20
Tags: #fleeting


  1. Using <img> element

Pros

  • Quick, familiar image syntax with built-in text equivalent available in the alt attribute.
  • You can make the image into a hyperlink easily by nesting the <img> inside an <a> element.
  • The SVG file can be cached by the browser, resulting in faster loading times for any page that uses the image loaded in the future.

Cons

  • You cannot manipulate the image with JavaScript.
  • If you want to control the SVG content with CSS, you must include inline CSS styles in your SVG code. (External stylesheets invoked from the SVG file take no effect.)
  • You cannot restyle the image with CSS pseudoclasses (like :focus).
  1. Paste SVG code inside in HTML
    Copy the .svg file using text editor
<svg width="300" height="200">
  <rect width="100%" height="100%" fill="green" />
</svg>

Pros

  • You can assign classes and ids to SVG elements and style them with CSS, either within the SVG or wherever you put the CSS style rules for your HTML document. In fact, you can use any SVG presentation attribute as a CSS property.
  1. Using iframe
<iframe src="triangle.svg" width="500" height="500" sandbox>
  <img src="triangle.png" alt="Triangle with three unequal sides" />
</iframe>

This is definitely not the best method to choose:

Cons

  • iframes do have a fallback mechanism, as you can see, but browsers only display the fallback if they lack support for iframes altogether.
  • Moreover, unless the SVG and your current webpage have the same origin, you cannot use JavaScript on your main webpage to manipulate the SVG.